﻿# -*-coding: UTF-8 -*-
import time

from Clover.CloverSystem import CloverSystem
from Clover.EngineSystemFactory import register_engine_module


@register_engine_module
class FpsStatSystem(CloverSystem):

	def __init__(self, engine):
		super().__init__(engine)
		# 性能监控
		self.start_time = 0
		self.frame_count = 0
		self.fps_time = 0
		self.current_fps = 0
		self.last_frame_time = 0
		# 帧时间统计
		self.frame_times = []
		self.average_frame_time = 0
		self.max_frame_time = 0
		self.max_frame_time_history = 60  # 保留最近60帧的时间

	def start(self):
		current_time = time.perf_counter()
		# 记录启动时间
		self.start_time = current_time
		self.last_frame_time = current_time
		self.set_current_fps(current_time)

	def post_tick(self, current_time, frame_time):
		self.last_frame_time = frame_time
		"""更新帧时间统计"""
		self.frame_times.append(frame_time)
		# 保持固定长度的历史记录
		if len(self.frame_times) > self.max_frame_time_history:
			self.frame_times.pop(0)
		self.average_frame_time = sum(self.frame_times) / len(self.frame_times) if self.frame_times else 0
		self.max_frame_time = max(self.frame_times) if self.frame_times else 0

	def set_current_fps(self, fps):
		self.current_fps = fps

	def destroy(self):
		up_time = self.get_uptime()
		self.logger.info(f'运行总时间: {up_time:.2f}s')

	@classmethod
	def get_current_fps(cls):
		return cls.Instance.current_fps

	@classmethod
	def get_average_frame_time(cls):
		"""获取平均帧时间（秒）"""
		fps_stat_system = cls.Instance
		if not fps_stat_system.frame_times:
			return 0
		return sum(fps_stat_system.frame_times) / len(fps_stat_system.frame_times)

	@classmethod
	def get_max_frame_time(cls):
		"""获取最大帧时间（秒）"""
		fps_stat_system = cls.Instance
		if not fps_stat_system.frame_times:
			return 0
		return max(fps_stat_system.frame_times)

	@classmethod
	def get_uptime(cls):
		"""获取应用程序运行时间（秒）"""
		fps_stat_system = cls.Instance
		return time.perf_counter() - fps_stat_system.start_time
